package cn.maxwell.org.controller;

import cn.maxwell.basic.util.BusinessException;
import cn.maxwell.basic.util.ExcelUtils;
import cn.maxwell.basic.util.JsonResult;
import cn.maxwell.basic.util.PageList;
import cn.maxwell.org.domain.Shop;
import cn.maxwell.org.dto.ShopDto;
import cn.maxwell.org.query.ShopQuery;
import cn.maxwell.org.service.IShopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/shop")
@Api(value = "员工的API",description="店铺相关的CRUD功能")
public class ShopController {

    @Autowired
    private IShopService shopService;

    /**
     * 查询所有
     *
     * @return
     */
    @GetMapping //get请求
    @ApiOperation(value = "查询所有")
    public List<Shop> loadAll() {
        return shopService.loadAll();
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}") //get请求，携带id参数
    @ApiOperation(value = "通过ID查询")
    //swagger注解：paramType="path"：解析path路径携带的参数；dataType="Long"：指定参数类型
    @ApiImplicitParam(name = "id", value = "编号", required = true, paramType = "path", dataType = "Long")
    public Shop loadById(@PathVariable("id") Long id) {//@PathVariable：获取path路径携带的参数
        return shopService.loadById(id);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     * @PathVariable:从发送的请求路径中拿到数据
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除操作")
    public JsonResult delete(@PathVariable("id") Long id) {
        try {
            shopService.delete(id);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }

    /**
     * 添加或修改
     *
     * @param shop
     * @return
     * @RequestBody：从请求体中拿到数据
     */
    @PutMapping()
    @ApiOperation(value = "添加或修改操作")
    public JsonResult save(@RequestBody Shop shop) {//@RequestBody:在请求体中获取参数
        try {
            if (shop.getId() == null) {
                shopService.add(shop);
            } else {
                shopService.update(shop);
            }
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }

    /**
     * 分页查询
     *
     * @param shopQuery
     * @return
     */
    @PostMapping()
    @ApiOperation(value = "分页查询")
    public PageList<Shop> query(@RequestBody ShopQuery shopQuery) {
        return shopService.queryPage(shopQuery);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "批量删除接口")
    public JsonResult patchDelete(@RequestBody List<Long> ids) { //List<Long>:要删除的id的集合
        try {
            shopService.patchDelete(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }

    @PostMapping("/settlement")
    //店铺入住
    //BusinessException:自定义异常类
    public JsonResult settlement(@RequestBody Shop shop) {
        try {
            shopService.settlement(shop);
            return JsonResult.me();
        } catch (BusinessException e) { //业务异常捕获
            return JsonResult.me().setMsg("入住失败" + e.getMessage());
        } catch (Exception e) { //其他异常（不可抗因素）
            e.printStackTrace();
            return JsonResult.me().setMsg("系统异常，请稍后再试");
        }
    }

    /**
     * 数据导出
     *
     * @param response
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            //调用查询所有方法获取店铺shop信息保存为list
            List<Shop> shops = shopService.loadAll();
            //店铺信息集合------excel标题-------页标题-------shop字节码文件------导出的Excel文件名----------
            ExcelUtils.exportExcel(shops, null, "店铺信息", Shop.class, "shop.xlsx", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件导入
     *
     * @param file
     */
    @PostMapping("/importExcel")
    public void importExcel(@RequestPart("file") MultipartFile file) {
        //String file = "F:\\文件名.xls";
        //解析excel，
        List<Shop> list = ExcelUtils.importExcel(file, 0, 1, Shop.class);
        //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
        System.out.println("导入数据一共【" + list.size() + "】行");
        for (Shop shop : list) {
            System.out.println(shop);
        }
        //保存到数据库中[自己实现，提示：动态sql 批量插入]
        shopService.patchInsert(list);
    }

    /**
     * 店铺echarts业务
     * @return
     */
    @GetMapping("/echarts")
    public List<ShopDto> getEchartsData(){
        List<ShopDto> shopDtos = shopService.getCountByState();
        return shopDtos;
    }
}